﻿using FastCode.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace FastCode.Helper
{
    public class PasswordHasherF
    {
        public static string GenerateJwtToken(User user, string secret, string issuer, string audience, int expireMins = 120)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                //new Claim(JwtRegisteredClaimNames.Sub, "subject"),
                //new Claim("role", "user"),
                new Claim(ClaimTypes.NameIdentifier,user.Id.ToString() ),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ConstData.PasswordLastUpdated, user.PasswordLastUpdated==null?string.Empty:user.PasswordLastUpdated.Value.ToString()),
                // 添加更多claims
            };

            var token = new JwtSecurityToken(issuer, audience, claims, expires: DateTime.Now.AddMinutes(expireMins), signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public static string ComputeHash(string password, string salt, int iteration = 1)
        {
            if (iteration <= 0) return password;

            using var sha256 = SHA256.Create();
            var passwordSaltPepper = $"{password}{salt}";
            var byteValue = Encoding.UTF8.GetBytes(passwordSaltPepper);
            var byteHash = sha256.ComputeHash(byteValue);
            var hash = Convert.ToBase64String(byteHash);
            return ComputeHash(hash, salt, iteration - 1);
        }
        public static string GenerateSalt()
        {
            using var rng = RandomNumberGenerator.Create();
            var byteSalt = new byte[16];
            rng.GetBytes(byteSalt);
            var salt = Convert.ToBase64String(byteSalt);
            return salt;
        }
    }
}
